using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace CKY.AgentPlatform.Performance
{
    /// <summary>
    /// 性能指标收集器
    /// 用于收集和统计应用程序的性能指标
    /// </summary>
    public class PerformanceMetrics
    {
        private readonly ConcurrentDictionary<string, ApiMetrics> _apiMetrics = new();
        private readonly ConcurrentDictionary<string, ErrorMetrics> _errorMetrics = new();
        private long _totalRequests;
        private long _totalErrors;
        private long _totalResponseTime;

        /// <summary>
        /// 记录API请求指标
        /// </summary>
        public void RecordRequest(string path, string method, int statusCode, long responseTimeMs)
        {
            Interlocked.Increment(ref _totalRequests);
            Interlocked.Add(ref _totalResponseTime, responseTimeMs);

            var key = $"{method}:{path}";
            var metrics = _apiMetrics.GetOrAdd(key, _ => new ApiMetrics());

            metrics.TotalRequests++;
            metrics.TotalResponseTime += responseTimeMs;
            metrics.MaxResponseTime = Math.Max(metrics.MaxResponseTime, responseTimeMs);
            metrics.MinResponseTime = metrics.MinResponseTime == 0 ? responseTimeMs : Math.Min(metrics.MinResponseTime, responseTimeMs);

            if (statusCode >= 400)
            {
                metrics.ErrorCount++;
                Interlocked.Increment(ref _totalErrors);
            }

            // 记录响应时间分布
            if (responseTimeMs < 100) metrics.FastCount++;
            else if (responseTimeMs < 1000) metrics.NormalCount++;
            else metrics.SlowCount++;
        }

        /// <summary>
        /// 记录错误指标
        /// </summary>
        public void RecordError(string path, string errorType)
        {
            var metrics = _errorMetrics.GetOrAdd(path, _ => new ErrorMetrics());
            metrics.ErrorCounts.AddOrUpdate(errorType, 1, (key, count) => count + 1);
        }

        /// <summary>
        /// 获取API性能统计
        /// </summary>
        public Dictionary<string, ApiMetrics> GetApiMetrics()
        {
            return _apiMetrics.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
        }

        /// <summary>
        /// 获取错误统计
        /// </summary>
        public Dictionary<string, ErrorMetrics> GetErrorMetrics()
        {
            return _errorMetrics.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
        }

        /// <summary>
        /// 获取总体性能统计
        /// </summary>
        public PerformanceSummary GetSummary()
        {
            var avgResponseTime = _totalRequests > 0 ? _totalResponseTime / _totalRequests : 0;
            var errorRate = _totalRequests > 0 ? (double)_totalErrors / _totalRequests * 100 : 0;

            return new PerformanceSummary
            {
                TotalRequests = _totalRequests,
                TotalErrors = _totalErrors,
                AverageResponseTime = avgResponseTime,
                ErrorRate = errorRate,
                Uptime = DateTime.UtcNow - _startTime
            };
        }

        /// <summary>
        /// 重置指标
        /// </summary>
        public void Reset()
        {
            _apiMetrics.Clear();
            _errorMetrics.Clear();
            Interlocked.Exchange(ref _totalRequests, 0);
            Interlocked.Exchange(ref _totalErrors, 0);
            Interlocked.Exchange(ref _totalResponseTime, 0);
            _startTime = DateTime.UtcNow;
        }

        private DateTime _startTime = DateTime.UtcNow;
    }

    /// <summary>
    /// API性能指标
    /// </summary>
    public class ApiMetrics
    {
        public long TotalRequests { get; set; }
        public long TotalResponseTime { get; set; }
        public long ErrorCount { get; set; }
        public long MaxResponseTime { get; set; }
        public long MinResponseTime { get; set; }
        public long FastCount { get; set; } // < 100ms
        public long NormalCount { get; set; } // 100-1000ms
        public long SlowCount { get; set; } // > 1000ms

        public double AverageResponseTime => TotalRequests > 0 ? (double)TotalResponseTime / TotalRequests : 0;
        public double ErrorRate => TotalRequests > 0 ? (double)ErrorCount / TotalRequests * 100 : 0;
    }

    /// <summary>
    /// 错误指标
    /// </summary>
    public class ErrorMetrics
    {
        public ConcurrentDictionary<string, int> ErrorCounts { get; } = new();
    }

    /// <summary>
    /// 性能统计摘要
    /// </summary>
    public class PerformanceSummary
    {
        public long TotalRequests { get; set; }
        public long TotalErrors { get; set; }
        public long AverageResponseTime { get; set; }
        public double ErrorRate { get; set; }
        public TimeSpan Uptime { get; set; }
    }
}